<?php
$gameId = $_GET['gameId'];
?>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="../../lib/layui-v2.8.12/src/layui.js"></script>
  <link rel="stylesheet" href="../../lib/layui-v2.8.12/src/css/layui.css">
  <script src="../../utils/form-serialize.js"></script>
  <script src="../../lib/axios/axios.min.js"></script>
  <link rel="stylesheet" href="../../css/common.css">
  <style>
    .layui-inline {
      margin-left: 100px;
    }
  </style>

  <title>Document</title>
</head>

<body>
  <!-- 给容器追加 class="layui-form-pane"，即可显示为方框风格 -->
  <form class="layui-form layui-form-pane" id="add" action="./addEvent.php?gameId=<?php echo $gameId; ?>" method="POST">
    <div class="layui-form-item">
      <div class="layui-inline">
        <label class="layui-form-label">进球球队</label>
        <div class="layui-input-inline">
          <select id="team" name="team" lay-filter="team" required>
          </select>
        </div>
      </div>
    </div>
    <div class="layui-form-item">
      <div class="layui-inline">
        <label class="layui-form-label">进球球员</label>
        <div class="layui-input-inline">
          <select id="player" name="player" lay-filter="player" required>
          </select>
        </div>
      </div>
    </div>

    <div class="layui-form-item">
      <div class="layui-inline">
        <label class="layui-form-label">进球时间</label>
        <div class="layui-input-inline">
          <input type="text" class="layui-input" autocomplete="off" name="time" id="time" placeholder="yyyy-MM-dd HH:mm:ss" required>
        </div>
      </div>
    </div>


    <div class="layui-form-item btn">
      <div>
        <button class="layui-btn" id="confirm">确认</button>
        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
      </div>
    </div>
  </form>
  <?php
  session_start();
  $user_id = $_SESSION['userId'];
  DEFINE('DB_USER', 'worldcup');
  DEFINE('DB_PASSWORD', '123456');
  DEFINE('DB_HOST', 'localhost');
  DEFINE('DB_NAME', 'worldcup');

  $dbc = @mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
  if (!$dbc) {
    die('Could not to connect to Mysql:' . mysqli_connect_error());
  }
  mysqli_set_charset($dbc, 'utf8');

  ?>
  <script>
    let gameId = <?php echo json_decode($gameId) ?>;

    //渲染下拉框
    layui.use(['laydate', 'form'], function() {
      var form = layui.form;
      var $ = layui.jquery;
      const renderSecond = (teamName) => {
        $.ajax({
          url: `../../php/getPlayerByTeamName.php?teamName=${teamName}`,
          dataType: 'json',
          headers: {
            'Content-Type': 'application/json;charset=UTF-8'
          },
          type: 'get',
          success: function(resData) {
            // console.log(resData.data);
            // 清空
            $('#player').empty();
            $.each(resData.data, function(index, value) {
              $('#player').append(new Option(value, value)); // 下拉菜单里添加元素
            });
            // //渲染select
            form.render('select');
          }
        });
      }
      $.ajax({
        url: `../../php/getTeamNameByGameId.php?gameId=${gameId}`,
        dataType: 'json',
        type: 'get',
        success: function(resData) {
          $('#team').empty();
          // console.log(resData.data);
          // console.log(1);
          $.each(resData.data, function(index, value) {
            $('#team').append(new Option(value, value)); // 下拉菜单里添加元素
          });
          var teamName = layui.$("#team").val();
          renderSecond(teamName);

          //渲染select
          form.render('select');
        }
      });

      // 第二步 监听父级，每当父级发生变化时，渲染子级的值
      form.on('select(team)', function(data) {
        let team = data.value;
        // console.log(groupNo);
        renderSecond(team);

      });

      //渲染时间选择器
      var laydate = layui.laydate;
      laydate.render({
        elem: '#time',
        type: 'datetime',
        fullPanel: true // 2.8+
      });
    })
  </script>

  <?php
  if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $team = $_POST['team'];
    $player = $_POST['player'];
    $time = $_POST['time'];

    $sql1 = "select team_id from team where team_name='{$team}';";
    $sql2 = "select player_id from player where player_name='{$player}';";
    $res1 = mysqli_query($dbc, $sql1);
    $res2 = mysqli_query($dbc, $sql2);
    $result1 = mysqli_fetch_assoc($res1);
    $result2 = mysqli_fetch_assoc($res2);
    $id1 = $result1['team_id'];
    $id2 = $result2['player_id'];
    // echo $id1, $id2;

    $sqlAdd = "insert into events(game_id,team_id,player_id,events_time,createdby) values($gameId,$id1,$id2,'{$time}',$user_id);";
    // echo $sqlAdd;
    $resAdd = mysqli_query($dbc, $sqlAdd);
    // echo mysqli_error($dbc);
    echo '<script>';
    if ($resAdd == 1) {
      echo '
        layui.use(\'layer\', function() {
          var layer = layui.layer;
          layer.msg(\'添加事件成功\');
          setTimeout(() => {
            var index = parent.layer.getFrameIndex(window.name); // 获取弹出层索引
            parent.layer.close(index); // 关闭弹出层
          }, 2000);
        });
      ';
    } else {
      echo '
        layui.use(\'layer\', function() {
          var layer = layui.layer;
          layer.msg(\'添加事件失败,请检查参数\');
          setTimeout(() => {
            var index = parent.layer.getFrameIndex(window.name); // 获取弹出层索引
            parent.layer.close(index); // 关闭弹出层
          }, 2000);
        });      
      ';
    }
    echo '</script>';
  }
  ?>
</body>

</html>